package cn.edu.zut.cs.Controller;

import cn.edu.zut.cs.Business.QiniuService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("images")
public class ImagupLoadController {

    @Autowired
    QiniuService qiniuService;


    /**
     * 上传文件到七牛云，并返回
     * 文件的url地址
     * @param file
     * @param imagename
     * @return
     */
    @RequestMapping("uploadimg")
    public String uploadimage(Model model, @RequestParam("fileup") MultipartFile file, @RequestParam("host") String imagename){
        String url = null;
        if (file == null) {
            System.out.println(url+"文件为空");
            model.addAttribute("fileurl",url);
            return "personpage";
        }
        try {
            //将文件转化为 byte[] 格式
            byte[] bytes = file.getBytes();
            //imagename为图片名称
            //先删除，再上传
//            qiniuService.deleteFileFromQiniu(imagename);
            String name= UUID.randomUUID().toString().replace("-","");
            String ext= FilenameUtils.getExtension(file.getOriginalFilename());
            String ur=name+"."+ext;
            url =qiniuService.uploadBybyte(bytes, ur);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(url + " 图片地址");
        //返回图片链接
        model.addAttribute("fileurl",url);
        return "personpage";
    }

    }

